<?php

namespace Biz\service\springHomeDecActivity;

use Biz\model\springHomeDecActivity\MSpringHomeDecWinningRecord;
use Biz\model\springHomeDecActivity\Wish as mWish;
use Biz\model\springHomeDecActivity\WishList as mWishList;
use Biz\pockets\constInterface\SpringHomeDecConfig;
use Doraemon\model\ForbiddenWord\ForbiddenSceneWord as ForbiddenSceneWordModel;
use Doraemon\service\ForbiddenWord\ForbiddenSceneWord;
use Doraemon\service\User;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Biz\service\ShopGoodsOperator;
use Biz\model\ShopFavorite as mShopFavorite;

class WishService implements SpringHomeDecConfig
{
    /**
     * 搭建家
     * @param $uid
     * @param $homePicId
     * @param $idea
     * @param $productIds
     * @return bool
     * @throws \Exception
     */
    public static function buildHome($uid, $homePicId, $idea, array $productIds)
    {
        try {
            if (empty($uid)) {
                throw new \Exception('登录后才能许愿！');
            }
            if (empty($homePicId)) {
                throw new \Exception('搭建家才能许愿！');
            }
            if (empty($idea)) {
                throw new \Exception('请输入住家理念感悟！');
            }
            if (empty($productIds) || !is_array($productIds)) {
                throw new \Exception('请选择许愿的商品或服务！');
            }

            //活动时间检查
            if (!ActivityService::running()) {
                throw new \Exception('活动已结束！');
            }

            //敏感词检测
            $ideaForbidden = new ForbiddenSceneWord(ForbiddenSceneWordModel::CONTENT, $idea, ForbiddenSceneWord::IDEA);
            if ($ideaForbidden->getHit() && !$ideaForbidden->getPublish()) {
                throw new \Exception('输入内容含有敏感词汇！');
            }

            //检查许愿商品数量
            WishListService::checkWishProductsCount($productIds);

            //检查许愿商品总价值
            WishListService::checkWishProductsValue($productIds);

            $time = date('Y-m-d H:i:s', time());
            $dataWish = [
                'uid' => $uid,
                'home_pic_id' => $homePicId,
                'idea' => $idea,
                'data_status' => mWish::STATUS_NORMAL,
                'lottery_remind' => mWish::LOTTERY_REMIND_NO,
                'create_time' => $time,
                'update_time' => $time,
            ];

            $productsMap = WishListService::getProductsMap($productIds);

            if (empty($productsMap)) {
                throw new \Exception('没有找到您要许愿的商品！');
            }

            $bResult = mWish::action(function () use ($dataWish, $productsMap) {
                $result = mWish::dataInsert($dataWish);
                if (!$result) {
                    return false;
                }
                $wishId = (int)$result;
                $dataWishList = [];
                foreach ($productsMap as $productId => $product) {
                    $dataWishList[] = [
                        'uid' => $dataWish['uid'],
                        'product_type' => (int)$product['product_type'],
                        'product_id' => (int)$productId,
                        'winning' => mWishList::WINNING_NO,
                        'data_status' => mWishList::STATUS_NORMAL,
                        'create_time' => $dataWish['create_time'],
                        'update_time' => $dataWish['update_time'],
                        'wish_id' => (int)$wishId,
                    ];
                }
                $result = mWishList::dataMultiInsert($dataWishList);
                if (!$result) {
                    return false;
                }
                return true;
            });
            if (!$bResult) {
                throw new \Exception('很遗憾，许愿失败了，请重试！');
            }

            //许愿商品自动加入收藏
            $is_favorite = mShopFavorite::is_favorited($uid, $productIds, mShopFavorite::TYPE_WIKI, 0);
            foreach ($productIds as $productId) {
                if ($productId == self::SERVICE_PRODUCT_ID) {
                    continue;
                }

                if ($is_favorite && $is_favorite[$productId]) {
                    continue;
                }
                ShopGoodsOperator::favorite($uid, $productId, mShopFavorite::TYPE_WIKI);
            }

        } catch (\Exception $e) {
            $errData = [
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ];
            Log::error('许愿失败', $errData);
            return false;
        }

        return true;
    }

    /**
     * 修改搭建家图片
     * @param $wishId
     * @param $uid
     * @param $homePicId
     * @return bool|int
     */
    public static function WishUpdate($wishId, $uid, $homePicId)
    {
        try {
            if (empty($wishId) || empty($uid) || empty($homePicId)) {
                throw new \Exception('参数错误');
            }
            $where['uid'] = $uid;
            $where['id'] = $wishId;
            $wish = mWish::dataSelectInfo($where);
            if (empty($wish)) {
                return false;
            }
            $updateData['home_pic_id'] = $homePicId;
            $updateData['update_time'] = date('Y-m-d H:i:s', time());
            $nResult = mWish::dataUpdate($updateData, $where);
            if (!$nResult) {
                throw new \Exception('修改搭建家图片保存失败');
            }
        } catch (\Exception $e) {
            $errData = [
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ];
            Log::error('修改搭建家图片失败', $errData);
            return false;
        }
        return true;
    }


    /**
     * 获取用户愿望
     * @param $uid
     * @return array|mixed
     */
    public static function userWish($uid)
    {
        $where['uid'] = $uid;
        $where['data_status'] = mWish::STATUS_NORMAL;
        $userWishInfo = [];
        $wish = mWish::dataSelectInfo($where);
        if ($wish && is_array($wish)) {
            $userWishInfo = $wish;
            $userWishInfo['home_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $wish['home_pic_id'],
                ImgUrl::IMAGE_SIZE_ORI_NPHONE);

            $userInfo = User::getBasicUserInfo($uid);
            $userWishInfo['user_info'] = [
                'uid' => (int)$userInfo['uid'],
                'nick' => $userInfo['nick'],
                'avatar' => $userInfo['avatar'],
                'small_avatar' => $userInfo['small_avatar'],
                'big_avatar' => $userInfo['big_avatar'],
            ];
            $wishProducts = WishListService::getWishProducts($uid);
            $userWishInfo['wish_products'] = $wishProducts;
            $userWishInfo['exchange_count'] = LuckyCharmTicketService::unExchangeTicketCount($uid);
            $userWishInfo['can_lottery'] = SSpringHomeDecLottery::getUserLotteryTimes($uid);
            //用户奖品数量
            $userWishInfo['winning_count'] = MSpringHomeDecWinningRecord::winningCount($uid);
        }
        return $userWishInfo;
    }

    public static function AllUserWish($page, $perPage = 20)
    {
        $where['data_status'] = mWish::STATUS_NORMAL;
        $where['ORDER'] = [
            'brick_count' => 'DESC',
            'id' => 'ASC',
        ];
        $dataList = [];
        $selectFields = [
            'id',
            'uid',
            'home_pic_id',
            'idea',
            'brick_count',
            'data_status',
            'create_time',
            'update_time'
        ];
        $wishs = mWish::dataPaginate($where, $selectFields, $page, $perPage);
        if ($wishs && is_array($wishs)) {
            $wishsIds = array_column($wishs, 'id');
            $wishProducts = WishListService::getWishProductsByWishIds($wishsIds,
                ['wish_id', 'product_id', 'product_type']);
            $uids = array_unique(array_column($wishs, 'uid'));
            $usersInfo = User::getBatchBasicUserInfo($uids);
            $usersInfoMap = !empty($usersInfo) ? array_column($usersInfo, null, 'uid') : [];
            foreach ($wishs as $wish) {
                $wish['home_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $wish['home_pic_id'],
                    ImgUrl::IMAGE_SIZE_A_PIC);
                $userInfo = $usersInfoMap[$wish['uid']] ?? [];
                $wish['user_info'] = [
                    'uid' => (int)$userInfo['uid'],
                    'nick' => $userInfo['nick'],
                    'avatar' => $userInfo['avatar'],
                    'small_avatar' => $userInfo['small_avatar'],
                    'big_avatar' => $userInfo['big_avatar'],
                ];
                $wish['wish_products'] = $wishProducts[$wish['id']] ?? [];
                $dataList[] = $wish;
            }
        }
        return $dataList;
    }

    /**
     * 心愿总数
     * @return int
     */
    public static function AllWishCount()
    {
        $where['data_status'] = mWish::STATUS_NORMAL;
        $count = mWish::dataCount($where);
        return $count;
    }

    /**
     * 抽奖提醒开关
     * @param $wishId
     * @param $remind
     * @return bool|int
     */
    public static function LotteryRemind($uid, $wishId, $remind)
    {
        $queryWhere['uid'] = $uid;
        $queryWhere['id'] = $wishId;
        $whish = mWish::dataSelectInfo($queryWhere);
        if (empty($whish)) {
            return false;
        }
        $data['lottery_remind'] = $remind;
        $data['update_time'] = date('Y-m-d H:i:s', time());
        $where['id'] = $wishId;
        $where['data_status'] = mWish::STATUS_NORMAL;
        return mWish::dataUpdate($data, $where);
    }


    /**
     * 用户砖块数
     * @param $uid
     * @return int[]
     */
    public static function userBrickCount($uid)
    {
        $where['uid'] = $uid;
        $where['data_status'] = mWish::STATUS_NORMAL;
        $result = mWish::dataSelectInfo($where, ['brick_count', 'exchange_brick_count']);
        $countArr = [
            'brick_count' => 0,
            'exchange_brick_count' => 0,
            'unexchange_brick_count' => 0,
        ];
        if ($result && is_array($result)) {
            $countArr['brick_count'] = $result['brick_count'];
            $countArr['exchange_brick_count'] = $result['exchange_brick_count'];
            $countArr['unexchange_brick_count'] = (int)$countArr['brick_count'] - (int)$countArr['exchange_brick_count'];
        }
        return $countArr;
    }


    /**
     * 增加已兑换砖块数量
     * @param $uid
     * @param $exchangeCount
     * @param $lastExchangeCount
     * @return bool
     */
    public static function addExchangeBrickCount($uid, $exchangeCount, $lastExchangeCount)
    {
        $data['exchange_brick_count'] = $lastExchangeCount + $exchangeCount;
        $data['update_time'] = date('Y-m-d H:i:s', time());
        $where['uid'] = $uid;
        $where['data_status'] = mWish::STATUS_NORMAL;
        $where['exchange_brick_count'] = $lastExchangeCount;
        $eCount = mWish::dataUpdate($data, $where, true);
        if ($eCount) {
            return true;
        }
        return false;
    }

    /**
     * 判断用户是否已许愿
     * @param $uid
     * @return bool
     */
    public static function hasWish($uid)
    {
        $where['uid'] = $uid;
        $where['data_status'] = mWish::STATUS_NORMAL;
        return mWish::dataHas($where);
    }

    /**
     * 获取用户许愿信息，不返回商品
     * @param $uid
     * @return mixed
     */
    public static function getUserWishInfo($uid)
    {
        $where['uid'] = $uid;
        $where['data_status'] = mWish::STATUS_NORMAL;
        return mWish::dataSelectInfo($where);
    }

}